//
//  ShopDetailViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/17.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "ShopDetailViewController.h"
#import "YBPopupMenu.h"
#import "NearShopCell.h"
#import "StoreViewController.h"
#import "AlertV.h"
#import "ProductModel.h"

@interface ShopDetailViewController ()<YBPopupMenuDelegate,UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UIButton *floorButton;
@property (weak, nonatomic) IBOutlet UIButton *zoneButton;
@property (weak, nonatomic) IBOutlet UIView *butonView;
@property(nonatomic,assign)BOOL flag;
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)YBPopupMenu *popupMenu;
@property(nonatomic,strong)AlertV *alertV;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)NSMutableArray *floorArray;
@property(nonatomic,strong)NSMutableArray *areaArray;
@property(nonatomic,strong)NSMutableDictionary *dic;

//参数楼层 区域
@property(nonatomic,copy)NSString *storeFloor;
@property(nonatomic,copy)NSString *storeArea;
@end

@implementation ShopDetailViewController

- (AlertV *)alertV{
    if(_alertV==nil){
        _alertV =[[[NSBundle mainBundle]loadNibNamed:@"AlertV" owner:self options:nil]lastObject];
        _alertV.layer.cornerRadius = 5;
        _alertV.layer.masksToBounds = YES;

        _alertV.centerX = Main_Screen_Width/2;
        _alertV.centerY = self.view.centerY;
    }
    return _alertV;
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_popupMenu dismiss];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.floorArray = [NSMutableArray array];
    self.dic = [NSMutableDictionary dictionary];
    
    self.dataSource = [NSMutableArray array];
    [self.floorButton setTitle:@"楼层" forState:UIControlStateNormal];
    [self.zoneButton setTitle:@"区域" forState:UIControlStateNormal];
    [self tableViewAndHeaderView];
    
    if(self.isComfromSearchVC){
        self.vcName =@"店铺搜索列表";
        [self loadSearchData];
    }else{
        [self loadFloor];
        self.storeFloor = @"";
        self.storeArea = @"";
        [self loadData];
    }
}

//3.6店铺注册--获取商场楼层接口
-(void)loadFloor{
    NSDictionary *paraDic = @{
                              @"marketId":self.marketId
                              };
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:MERCHANTSELECTEFLOOR paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取商场楼层接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *market = resultDic[@"data"];
            if([market isKindOfClass:[NSNull class]]) return ;
            if(market.count){
                ProductModel *model = [[ProductModel alloc]init];
                model.name = @"全部";
                [weakSelf.floorArray addObject:model];
                for(NSDictionary *dic in market){
                    ProductModel *pmodel = [[ProductModel alloc]init];
                    pmodel.name = dic[@"floorNum"];
                    [weakSelf.floorArray addObject:pmodel];
                }
                //加载 楼层的默认区域
                ProductModel *pmodel  = weakSelf.floorArray.firstObject;
                weakSelf.storeFloor = pmodel.name;
                [weakSelf loadArea];
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
//3.7店铺注册--获取商场楼层区域接口
-(void)loadArea{
    NSDictionary *paraDic = @{
                              @"marketId":self.marketId,
                              @"floor": self.storeFloor,
                              };
    __weak typeof(self)  weakSelf = self;
    [Tools AFNetworkingRequestTypePostWithUrl:MERCHANTSELECTEAREA paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"获取商场楼层区域接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *market = resultDic[@"data"];
            if([market isKindOfClass:[NSNull class]]) return ;
            if(market.count){
                NSMutableArray *area = [NSMutableArray array];
                ProductModel *model = [[ProductModel alloc]init];
                model.name = @"全部";
                [area addObject:model];
                for(NSDictionary *dic in market){
                    ProductModel *pmodel = [[ProductModel alloc]init];
                    pmodel.name = dic[@"areaName"];
                    [area addObject:pmodel];
                }
                weakSelf.areaArray= area;
                [weakSelf.dic setObject:area forKey:self.storeFloor];
            }
        }else{
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

    //2.10店铺查询接口（店铺列表)
-(void)loadSearchData{
    NSDictionary * paraDic= @{@"storeName":self.shopName};
    __weak typeof(self)  weakSelf = self;
    [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:SELECTBYSTORENAME paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
          DLog(@"店铺搜索结果----%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *listArr = resultDic[@"data"];
            if([listArr isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismissHUD];
                return ;
            }
            for(NSDictionary *dic in listArr){
                NearShopModel *model = [[NearShopModel alloc]init];
                model.storeHeader = dic[@"storeHeader"];
                model.storePic= dic[@"storePic"];
                model.introduce = dic[@"storeIntroduce"];
                model.name = dic[@"storeName"];
                model.id = dic[@"storeId"];
                model.address = dic[@"Address"];
                model.isLive = dic[@"liveState"];
                [weakSelf.dataSource addObject:model];
            }
            if(!weakSelf.dataSource.count){
                [MBProgressHUD dismissHUD];
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
                return;
            }else{
                [weakSelf.noDataIUmageV removeFromSuperview];
            }

            [weakSelf.tableV reloadData];
            weakSelf.tableV.hidden = NO;
            [MBProgressHUD dismissHUD];
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

-(void)loadData{
    //2.8商场详情（商场店铺展示）接口
       NSDictionary *paraDic = @{
                              @"marketId":self.marketId,
                              @"storeFloor":_storeFloor,
                              @"storeArea":_storeArea
                              };
    
    __weak typeof(self)  weakSelf = self;
   [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:DETAILMAERKET paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
           DLog(@"2.8商场详情（商场店铺展示）接口--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *dataArray = resultDic[@"data"];
            if([dataArray isKindOfClass:[NSNull class]]) {
                [MBProgressHUD dismissHUD];
                return ;
            }
            if(weakSelf.dataSource.count){
                [weakSelf.dataSource removeAllObjects];
            }
            for(NSDictionary *dic in dataArray){
                NearShopModel *model = [[NearShopModel  alloc]init];
                model.isLive = dic[@"liveState"];
                model.address = dic[@"marketAddress"];
                model.storeHeader = dic[@"storeHeader"];
                model.id = dic[@"storeId"];
                model.introduce = dic[@"storeIntroduce"];
                model.name = dic[@"storeName"];
                model.storePic = dic[@"storePics"];
                [weakSelf.dataSource addObject:model];
            }
            if(!weakSelf.dataSource.count){
                [MBProgressHUD dismissHUD];
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
                 weakSelf.tableV.hidden = YES;
                return;
            }else{
                [weakSelf.noDataIUmageV removeFromSuperview];
            }
            [weakSelf.tableV reloadData];
            weakSelf.tableV.hidden = NO;
            [MBProgressHUD dismissHUD];
            [weakSelf performSelector:@selector(showAlert) withObject:nil afterDelay:.8];
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}
-(void)showAlert{
    NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
    BOOL value = [useDefault boolForKey:@"isNeedToShowAlert"];
    if(value==NO){//默认 提醒
        [self alert_V];
    }
}


- (void)alert_V{
    UIWindow *window = (UIWindow*)[UIApplication sharedApplication].keyWindow;
    [window addSubview:self.maskV];
    [window addSubview:self.alertV];
    self.maskV.userInteractionEnabled = YES;
    __weak typeof (self) weakSelf = self;
    _alertV.leftBlock=^{
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.alertV removeFromSuperview];
    };
    _alertV.rightBlock=^{
        NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
        [useDefault setBool:YES forKey:@"isNeedToShowAlert"];
        //同步数据
        [useDefault synchronize];
        [weakSelf.maskV removeFromSuperview];
        [weakSelf.alertV removeFromSuperview];
    };
}

- (void)tableViewAndHeaderView{
    //表视图
    if(self.isComfromSearchVC){
        self.butonView.hidden = YES;
         _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight) style:UITableViewStylePlain];
    }else{
         _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, self.butonView.bottom, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight-self.butonView.height) style:UITableViewStylePlain];
    }
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = DEF_COLOR242;
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
    _tableV.tableFooterView = [[UIView alloc]init];
    _tableV.hidden = YES;
}

- (IBAction)floor:(UIButton *)sender {
    if(self.zoneButton.selected&&_popupMenu!=nil){
         [self zone:self.zoneButton];
        _popupMenu = nil;
        return;
    }
    self.flag =YES;
    sender.selected = !sender.selected;
    if(sender.isSelected){
        _popupMenu = [YBPopupMenu  showAtPoint:CGPointMake(0, self.butonView.bottom) titles:self.floorArray icons:nil menuWidth:sender.width view:self.view  delegate:self];
        _popupMenu.backGroudColor = [UIColor whiteColor];
        _popupMenu.isShowSeparator = YES;
           _popupMenu.text_Color = [UIColor blackColor];
        _popupMenu.seperaterColor = [UIColor colorWithRed:234./255 green:234./255 blue:234./255 alpha:1.];
        [self.floorButton setImage:[UIImage imageNamed:@"icon_shangchangxiala_sel-"] forState:UIControlStateSelected];
    }else{
         [_popupMenu dismiss];
          [self.floorButton setImage:[UIImage imageNamed:@"icon_shangchangxiala_nor"] forState:UIControlStateNormal];
    }
}

- (IBAction)zone:(UIButton *)sender {
    if(self.floorButton.selected&&_popupMenu!=nil){
        [self floor:self.floorButton];
        _popupMenu = nil;
        return;
    }
    self.flag =NO;
    sender.selected = !sender.selected;
    if(sender.isSelected){
       _popupMenu = [YBPopupMenu  showAtPoint:CGPointMake(sender.left, self.butonView.bottom) titles:self.areaArray icons:nil menuWidth:sender.width view:self.view  delegate:self];
        _popupMenu.backGroudColor = [UIColor whiteColor];
        _popupMenu.isShowSeparator = YES;
        _popupMenu.text_Color = [UIColor blackColor];
       _popupMenu.seperaterColor = [UIColor colorWithRed:234./255 green:234./255 blue:234./255 alpha:1.];
        [self.zoneButton setImage:[UIImage imageNamed:@"icon_shangchangxiala_sel-"] forState:UIControlStateSelected];
    }else{
        [_popupMenu dismiss];
        [self.zoneButton setImage:[UIImage imageNamed:@"icon_shangchangxiala_nor"] forState:UIControlStateNormal];
    }
}


#pragma mark - YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
    if(_flag){
        [self zone:self.floorButton];
         ProductModel *model = self.floorArray[index];
           [self.floorButton setTitle:model.name  forState:UIControlStateNormal];
        if([model.name isEqualToString:@"全部"]){
            self.storeFloor = @"";
        }else{
            self.storeFloor = model.name;
        }
        [self loadData];
        NSMutableArray *area =  self.dic[model.name];
        if(area==nil){
            [self loadArea];
        }else{
            self.areaArray = area;
        }
        DLog(@"点击了 %@ 选项",model.name);
    }else{
        [self zone:self.zoneButton];
        ProductModel *model = self.areaArray[index];
        [self.zoneButton setTitle:model.name  forState:UIControlStateNormal];
        if([model.name isEqualToString:@"全部"]){
            self.storeArea = @"";
        }else{
            self.storeArea = model.name;
        }
        [self loadData];
        DLog(@"点击了 %@ 选项",model.name);
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"acqtell";
    NearShopCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"NearShopCell" owner:self options:nil]lastObject];
    }
    cell.isLive = YES;
    cell.isShowRightBottonButn = YES;
    cell.isShowDistance = NO;
    cell.model = self.dataSource[indexPath.row];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    StoreViewController *goodsDetail  = [[StoreViewController alloc]init];
    NearShopModel *model = self.dataSource[indexPath.row];
    goodsDetail.storeId = model.id;
    goodsDetail.vcName = model.name;
    [self.navigationController pushViewController:goodsDetail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
